import csv, time, os


def menu():
    print('----欢迎使用BMI计算程序----')
    print('1. 进入计算器')
    print('2. 退出程序')
    print('3. 重新生成储存BMI计算数据的CSV文件表头')


def calculate_bmi(height, weight):
    if height < 3:
        bmi = weight / (height ** 2)
        if bmi < 18.5:
            who, nat = "偏瘦", "偏瘦"
        elif 18.5 <= bmi < 24:
            who, nat = "正常", "正常"
        elif 24 <= bmi < 25:
            who, nat = "正常", "偏胖"
        elif 25 <= bmi < 28:
            who, nat = "偏胖", "偏胖"
        elif 28 <= bmi < 30:
            who, nat = "偏胖", "肥胖"
        else:
            who, nat = "肥胖", "肥胖"
    if height > 3:
        bmi = weight / ((height / 100) ** 2)
        if bmi < 18.5:
            who, nat = "偏瘦", "偏瘦"
        elif 18.5 <= bmi < 24:
            who, nat = "正常", "正常"
        elif 24 <= bmi < 25:
            who, nat = "正常", "偏胖"
        elif 25 <= bmi < 28:
            who, nat = "偏胖", "偏胖"
        elif 28 <= bmi < 30:
            who, nat = "偏胖", "肥胖"
        else:
            who, nat = "肥胖", "肥胖"

    # return将这三个值作为一个元组返回给函数的调用者。
    return bmi, who, nat


def calculate_bmr(sex, height, weight, age):
    global bmr
    if height > 3:
        if sex == '女':
            bmr = 655 + (9.6 * weight) + (5 * height) - (6.8 * age)
        elif sex == '男':
            bmr = 66 + (13.7 * weight) + (1.8 * height) - (6.8 * age)
    elif height < 3:
        if sex == '女':
            bmr = 655 + (9.6 * weight) + (500 * height) - (6.8 * age)
        elif sex == '男':
            bmr = 66 + (13.7 * weight) + (5 * height) - (6.8 * age)
    return bmr


def count():
    search_count = 0  # 统计正确查询次数
    incorrect_count = 0  # 统计不正确的查询次数
    data = []  # 定义一个空列表，存储BMI计算数据

    while True:
        name = input('请输入您的姓名: ')
        try:
            # eval() 函数可以使字符串被当作有效的表达式进行求值，将结果赋值给 height 和 weight 变量。
            # split(',') 方法将用户输入的字符串按逗号 , 进行分割，生成一个列表。
            # map(float, ...)函数将列表中的每个子字符串转换为浮点数类型。
            height, weight = map(float, input("请输入身高(米/厘米)和体重(公斤)[逗号隔开]: ").split(','))
            age = int(input("请输入年龄: "))  # 获取用户输入的年龄，并将其转换为整数类型。
            if age <= 0:
                raise ValueError  # raise用于手动触发异常,ValueError异常适用于与特定值相关的错误
        except ValueError:
            print("输入格式错误，请重新输入")
            incorrect_count += 1  # 增加不正确的查询次数
            continue  # 会立即跳过当前循环的剩余代码，然后进入下一次循环的开始处。
        while True:
            sex = input('请输入你的性别(男/女): ')
            if sex == '男' or sex == '女':
                break
            else:
                print("无效的性别，请重新输入")
                incorrect_count += 1
                break  # 退出当前循环，重新开始下一次循环
        sex = input('请输入你的性别(男/女): ')
        # 调用函数calculate_bmi(height, weight)，用身高和体重计算bmi和判断bmi标准
        bmi, who, nat = calculate_bmi(height, weight)
        bmr = calculate_bmr(sex, height, weight, age)
        search_count, incorrect_count = print_statistics(search_count, incorrect_count)
        # time.time() 返回当前时间的时间戳
        # time.localtime() 将其转换为本地时间的结构化时间对象。
        # time.asctime() 将结构化时间对象转换为字符串表示。
        # 格式化：nowtime = time.strftime("%Y-%m-%d %H:%M:%S %A", time.localtime(time.time()))
        nowtime = time.asctime(time.localtime(time.time()))
        if sex == '女':
            print('感谢', name, '女士在', nowtime, '使用本程序,祝您身体健康!')
        elif sex == '男':
            print('感谢', name, '先生在', nowtime, '使用本程序,祝您身体健康!')
        else:
            print("无效的性别，请重新输入")
            incorrect_count += 1
            continue  # 输入错误性别，会立即跳过当前循环的剩余代码，然后进入下一次循环的开始处。

        search_count += 1
        # data是列表，.append() 是一个列表对象的方法，用于添加元素。
        data.append([name, height, weight, age, sex, bmi, who, nat, nowtime, bmr])

        user_input = input("输入 'n' 停止循环: ")
        if user_input == 'n':
            break

    # 将数据保存到CSV文件
    filename = "bmi_data.csv"  # 文件名
    file_exists = os.path.isfile(filename)  # 调用函数，文件是否存在
    # open打开文件bmi_data.csv
    #  "a" 继续输入数据
    # newline=""，使用一个空字符串作为行尾符号，以确保在写入文件时不添加额外的换行符。
    with open(filename, "a", newline="") as file:
        # 创建一个 CSV 写入器对象writer，并将它与文件对象 file 关联起来。
        writer = csv.writer(file)
        if not file_exists:  # 空文件
            writer.writerow(["姓名", "身高(米)", "体重(公斤)", "年龄", "性别", "BMI", "国际", "国内", "查询时间", "BMR"])
        writer.writerows(data)
    print("BMI计算数据已保存至", filename)


def list_start():
    # 在菜单栏里输入3，调用list_start()函数生成表头。
    filename = "bmi_data.csv"
    with open(filename, "a", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["姓名", "身高(米)", "体重(公斤)", "年龄", "性别", "BMI", "国际", "国内", "查询时间", "BMR"])
    print("CSV文件表头已生成：", filename)


def print_statistics(search_count, incorrect_count):
    sum_count = search_count + incorrect_count
    print("您的查询次数为", sum_count, "次")
    print("其中正确的查询次数为", search_count, "次")
    print("其中不正确的查询次数为", incorrect_count, "次")
    return search_count, incorrect_count


def main():
    while True:
        menu()
        choice = input("请输入选项: ")

        if choice == '1':
            # 调用count函数
            count()
        elif choice == '2':
            print("程序已退出")
            break
        elif choice == '3':
            list_start()
        else:
            print("无效的选项，请重新输入")


if __name__ == "__main__":
    main()
